package org.penguin.study.bk.elasticsearch.controller;

import org.penguin.study.bk.base.vo.Result;
import org.penguin.study.bk.elasticsearch.entity.Product;
import org.penguin.study.bk.elasticsearch.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author chengyinghua
 */
@RestController
@RequestMapping("/elasticsearch")
@ConditionalOnProperty(name = "elasticsearch.enable", havingValue = "true")
public class ProductController {

    @Autowired
    private ProductService productService;

    @PostMapping("/add")
    public Result<?> add(@RequestBody Product product) {
        productService.createProductIndex(product);
        return Result.ok(product);
    }

    @GetMapping("/list")
    public Result<Iterable<Product>> getAll() {
        return Result.ok(productService.getAll());
    }

    @GetMapping("/name")
    public Result<List<Product>> findByName(@RequestParam(defaultValue = "红旗H5") String name) {
        return Result.ok(productService.findByName(name));
    }

    @GetMapping("/manufacturer")
    public Result<List<SearchHit<Product>>> findProductsByManufacturer(@RequestParam(defaultValue = "红旗") String name) {
        return Result.ok(productService.findProductsByManufacturer(name));
    }

    @GetMapping("/price")
    public void searchByPrice(@RequestParam(defaultValue = "0.9") Double min, @RequestParam(defaultValue = "100.9") Double max) {
        productService.findByProductPrice(min, max);
    }
}
